<?php
namespace mytp;

// 响应类,负责响应处理
class Response{

  protected $codes = 200;       // 状态码
  protected $header = [];       // 响应头
  protected $data = '';         // 响应内容

  public function __construct($data = '', $code = 200, array $header = []) {
    $this->data = $data;
    $this->code = $code;
    $this->header = array_merge($this->header, $header);
  }

  public function send() {
    http_response_code($this->code);
    foreach ($this->header as $name => $value){
      header($name.(is_null($value) ? '' : ':'.$value));
    }
    // var_dump($this->data);
    if(!empty($this->header['code'])) {
      echo $this->data;
    }
    // if(empty($this->data)) exit(json_encode(false));
    // 响应结果的输出最终形态( json数据格式)
    exit(json_encode($this->data));
  }

  // 编写一个静态方法,用于构建自身
  public static function create($data = '', $code = 200, array $header = []) {
    return new static($data, $code, $header);
  }
}
?>